package com.ruoyi.flink.chapten5;

import java.util.Random;

/**
 * Copyright (c) 2020-2030 尚硅谷 All Rights Reserved
 * <p>
 * Project:  FlinkTutorial
 * <p>
 * Created by  wushengran
 */

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;

public class SourceCustomTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //有了自定义的source function，调用addSource方法
        // DataStreamSource<Event> stream = env.addSource(new ClickSource());
       DataStreamSource<Integer> stream = env.addSource(new ParallelCustomSource()).setParallelism(2);
        stream.print();

        env.execute();
    }
    
    // 实现自定义并行的SourceFunction
    public static class ParallelCustomSource implements ParallelSourceFunction<Integer>{
        
    	private Boolean runing = true;
    	private Random random = new Random();		
		@Override
		public void run(SourceContext<Integer> ctx) throws Exception {
			while (runing) {
				ctx.collect(random.nextInt());
				
			}
			
		}

		@Override
		public void cancel() {
			runing = false;
			
		}
    	
    }
    
    
    
}

